//
//  RecommendControllerViewController.m
//  ProductB
//
//  Created by 田阳 on 16/8/5.
//  Copyright © 2016年 田阳. All rights reserved.
//

#import "RecommendController.h"
#import "RecommendHeaderView.h"
#import "RecommendSessionView.h"
#import "RecommendCell.h"
#import "RecommendModel.h"
#import "ViwepagerModel.h"
#import "FirstCellModel.h"
#import "GoodListCell.h"
#import "GoodListModel.h"
#import "LastCell.h"
#import "RecommendFirstCell.h"
#import "ButtonView.h"
#import "XiaoBianMoreTableViewController.h"
#import "CategoryController.h"
#import "TrackListDetailViewController.h"
#import "ListenMoreViewController.h"
#import "RecommendCategoryModel.h"
#import "ProgramListViewController.h"
#import "OtherProgramViewController.h"
#import "GoodListenListTableViewController.h"

//item大小
#define ItemSize  (kScreenWidth - 30) / 3
@interface RecommendController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,UIScrollViewDelegate>
@property(nonatomic,strong) UICollectionView *collectionView;
@property(nonatomic,strong) UICollectionViewFlowLayout *flowLayout;
//存放小编推荐model数组
@property(nonatomic,strong) NSMutableArray *modelArray;
//存放轮播图model数组
@property(nonatomic,strong) NSMutableArray *imageViewArray;
//第一个section头视图(轮播图)
@property(nonatomic,strong) RecommendHeaderView *headerView;
//存放第一个Cell的model
@property(nonatomic,strong) NSMutableArray *firstModelArray;
//存放所有数组的字典
@property(nonatomic,strong) NSMutableDictionary *arrayDic;
//定时器
@property(nonatomic,strong) NSTimer *timer;
@property(nonatomic,assign) NSInteger index;
//存放所有分区标题数组
@property(nonatomic,strong) NSArray *titleArray;
//第一个item视图
@property(nonatomic,strong) RecommendFirstCell *cell;
// 存放跳转更多界面的keyName数组
@property (nonatomic, strong) NSMutableArray *keyArray;
// 存放跳转更多界面的categoryID数组
@property (nonatomic, strong) NSMutableArray *categoryIdArray;
// 存放听上海code
@property (nonatomic, strong) NSString *code;



@end

@implementation RecommendController

- (NSMutableArray *)categoryIdArray
{
    if (!_categoryIdArray) {
        _categoryIdArray = [[NSMutableArray alloc] init];
    }
    return _categoryIdArray;
}

- (NSMutableArray *)keyArray
{
    if (!_keyArray) {
        _keyArray = [[NSMutableArray alloc] init];
    }
    return _keyArray;
}

- (NSMutableDictionary *)arrayDic
{
    if (!_arrayDic) {
        self.arrayDic = [[NSMutableDictionary alloc] init];
    }
    return _arrayDic;
}

- (NSMutableArray *)firstModelArray
{
    if (!_firstModelArray) {
        self.firstModelArray = [[NSMutableArray alloc] init];
    }
    return _firstModelArray;
}

- (NSMutableArray *)imageViewArray
{
    if (!_imageViewArray) {
        self.imageViewArray = [[NSMutableArray alloc] init];
    }
    return _imageViewArray;
}

- (NSMutableArray *)modelArray
{
    if (!_modelArray) {
        self.modelArray = [[NSMutableArray alloc] init];
    }
    return _modelArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.titleArray = @[@"付费精品",@"听资讯",@"听小说",@"听脱口秀",@"听娱乐",@"听相声",@"听音乐",@"听情感心声",@"听历史人文",@"听外语",@"听广播剧",@"听儿童故事",@"听旅游",@"听公开课",@"听动漫游戏",@"听时尚生活",@"听健康"];
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self dataRequestWithItem];
    [self creatCollectionView];
//    [self creatBackgroundView];
}

- (void)creatBackgroundView
{
    UIImageView *imageV = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    imageV.image = [UIImage imageNamed:@"002.jpg"];
    UIToolbar *toolbar = [[UIToolbar alloc] initWithFrame:imageV.frame];
    toolbar.barStyle = UIBarStyleBlackTranslucent;
    [imageV addSubview:toolbar];
    self.collectionView.backgroundView = imageV;
}

- (void)creatCollectionView
{
    self.flowLayout = [[UICollectionViewFlowLayout alloc] init];
    _flowLayout.minimumLineSpacing = 0;
    _flowLayout.minimumInteritemSpacing = 0;

    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 114 - kScreenHeight / 20) collectionViewLayout:_flowLayout];
    _collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    //注册cell及相应的头视图
    [self.collectionView registerNib:[UINib nibWithNibName:@"ViewpagerCell" bundle:nil] forCellWithReuseIdentifier:@"firstCell"];
    [self.collectionView registerNib:[UINib nibWithNibName:@"RecommendCell" bundle:nil] forCellWithReuseIdentifier:@"recommendCell"];
    [self.collectionView registerClass:[RecommendSessionView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerView"];
    [self.collectionView registerNib:[UINib nibWithNibName:@"GoodListCell" bundle:nil] forCellWithReuseIdentifier:@"goodListCell"];
    [self.collectionView registerNib:[UINib nibWithNibName:@"RecommendFirstCell" bundle:nil] forCellWithReuseIdentifier:@"myCell"];
    [self.collectionView registerClass:[RecommendHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headView"];
    [self.collectionView registerNib:[UINib nibWithNibName:@"LastCell" bundle:nil] forCellWithReuseIdentifier:@"lastCell"];
    [self.view addSubview:_collectionView];
}


- (void)dataRequestWithItem
{
    [NetWorkrequestManage requestWithType:GET url:EidetRecommendURL parameters:nil finish:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
        //小编推荐
        NSArray *array = dic[@"editorRecommendAlbums"][@"list"];
        for (NSDictionary *dict in array) {
            XiaoBianMoreModel *model = [[XiaoBianMoreModel alloc] init];
            [model setValuesForKeysWithDictionary:dict];
            [self.modelArray addObject:model];
            NSLog(@"o8098051%@",_modelArray); 
        }
        [self.arrayDic setValue:_modelArray forKey:@"first"];
        
        //获取轮播图
        NSArray *imageArray = dic[@"focusImages"][@"list"];
        
        for (NSDictionary *dict in imageArray) {
            ViwepagerModel *model = [[ViwepagerModel alloc] init];
            [model setValuesForKeysWithDictionary:dict];
            [self.imageViewArray addObject:model];
        }
        [self.arrayDic setValue:self.imageViewArray forKey:@"third"];
        
        //精品听单
        NSMutableArray *goodArray = [[NSMutableArray alloc] init];
        NSArray *goodListArray = dic[@"specialColumn"][@"list"];
        for (NSDictionary *dict in goodListArray) {
            GoodListModel *model = [[GoodListModel alloc] init];
            [model setValuesForKeysWithDictionary:dict];
            [goodArray addObject:model];
        }
        [self.arrayDic setValue:goodArray forKey:@"精品听单"];
        [self dataRequestWithUrl];
    } error:nil];
}

- (void)dataRequestWithUrl
{
    [NetWorkrequestManage requestWithType:GET url:CategoryItemURL parameters:nil finish:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
        NSArray *array = dic[@"discoveryColumns"][@"list"];
        //轮播图下9个item
        for (NSDictionary *dict in array) {
            FirstCellModel *model = [[FirstCellModel alloc] init];
            [model setValuesForKeysWithDictionary:dict];
            [self.firstModelArray addObject:model];
        }
        //将解析出来的数组加入字典
        [self.arrayDic setValue:self.firstModelArray forKey:@"second"];
        
        //听上海
        NSMutableArray *modelArray = [[NSMutableArray alloc] init];
        self.code = dic[@"cityColumn"][@"code"];
        
        NSArray *array1 = dic[@"cityColumn"][@"list"];
        
        for (NSDictionary *dict in array1) {
            XiaoBianMoreModel *model = [[XiaoBianMoreModel alloc] init];
            [model setValuesForKeysWithDictionary:dict];
            [modelArray addObject:model];
        }
        [self.arrayDic setValue:modelArray forKey:@"听上海"];
        
        //热门推荐
        NSInteger index = 0;
        NSArray *hotArray = dic[@"hotRecommends"][@"list"];
        for (NSDictionary *dict in hotArray) {
            NSMutableArray *modelArray = [[NSMutableArray alloc] init];
            RecommendCategoryModel *model = [[RecommendCategoryModel alloc] init];
            [model setValuesForKeysWithDictionary:dict];
            [self.categoryIdArray addObject:model];
            
            for (NSDictionary *dicti in dict[@"list"]) {
                RecommendModel *model = [[RecommendModel alloc] init];
                [model setValuesForKeysWithDictionary:dicti];
                [modelArray addObject:model];
            }
            [self.arrayDic setObject:modelArray forKey:self.titleArray[index]];
            index++;
        }
        //判断当字典长度等于四时，刷新视图
        if (self.arrayDic.count == 22) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.collectionView reloadData];
            });
        }
    } error:nil];
}

#pragma mark ----collectionView delegate方法
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return self.arrayDic.count - 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }else if (section == 1){
        return self.modelArray.count;
    }else if (section == 2){
        NSArray *arr = self.arrayDic[@"听上海"];
        return arr.count;
    }else if (section == 3){
        NSArray *arr = self.arrayDic[@"精品听单"];
        return arr.count;
    }else{
        NSString *str = self.titleArray[section - 4];
        NSArray *arr = self.arrayDic[str];
        return arr.count;
    }
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return CGSizeMake(kScreenWidth, 150);
    }else{
        return CGSizeMake(kScreenWidth, 40);
    }
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return CGSizeMake(kScreenWidth, kScreenWidth / 5 + 30);
    }else if(indexPath.section == 3){
        return CGSizeMake(kScreenWidth - 30, 90);
    }else{
        return CGSizeMake(ItemSize, ItemSize + 70);
    }
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.section == 0) {
         self.headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headView" forIndexPath:indexPath];
        
        NSMutableArray *array = [[NSMutableArray alloc] init];
        for (NSInteger i = 0; i < self.imageViewArray.count; i++) {
            ViwepagerModel *model = self.imageViewArray[i];
            [array addObject:model.pic];
        }
        CarouselView *carouelView = [[CarouselView alloc] initWithFrame:self.headerView.imageScrollView.frame imageURLs:array];

        [self.headerView.imageScrollView addSubview:carouelView];
        return _headerView;
    }else{
        RecommendSessionView *sessionView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerView" forIndexPath:indexPath];
        if (indexPath.section == 1) {
            sessionView.titleLabel.text = @"小编推荐";
        }else if (indexPath.section == 2) {
            sessionView.titleLabel.text = @"听上海";
        }else if (indexPath.section == 3){
            sessionView.titleLabel.text = @"精品听单";
        }else{
            sessionView.titleLabel.text = self.titleArray[indexPath.section - 4];
        }
        sessionView.button.tag = indexPath.section;
        [sessionView.button addTarget:self action:@selector(btnAction:) forControlEvents:(UIControlEventTouchUpInside)];
        return sessionView;
    }
}



- (void)btnAction:(UIButton *)btn {
    if (btn.tag == 1) {
        XiaoBianMoreTableViewController *vc = [[XiaoBianMoreTableViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
    if (btn.tag > 3 && btn.tag < 22) {
        ListenMoreViewController *vc = [[ListenMoreViewController alloc] init];
        vc.type = @"others";
        RecommendCategoryModel *model = self.categoryIdArray[btn.tag - 4];
        vc.categoryId = model.categoryId;
        vc.myTitle = model.title;
        [self.navigationController pushViewController:vc animated:YES];
    }
    if (btn.tag == 2) {
        ListenMoreViewController *vc = [[ListenMoreViewController alloc] init];
        vc.type = @"听";
        vc.code = self.code;
        [self.navigationController pushViewController:vc animated:YES];
    }
    
}

- (void)setupFirstCell
{
    _cell.myScrollView.contentSize = CGSizeMake(self.firstModelArray.count * (kScreenWidth / 5 + 20), 0);
    _cell.myScrollView.showsHorizontalScrollIndicator = NO;
    
    for (NSInteger i = 0; i < self.firstModelArray.count - 1; i++) {
        ButtonView *btnView = [[ButtonView alloc] initWithFrame:CGRectMake(5 + i * kScreenWidth / 5 + i * 20, 0, kScreenWidth / 5, kScreenWidth / 5 + 30)];
        FirstCellModel *model = self.firstModelArray[i];
        [btnView.imageV sd_setImageWithURL:[NSURL URLWithString:model.coverPath]];
        
        btnView.label.text = model.title;
        [_cell.myScrollView addSubview:btnView];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapClick:)];
        btnView.tag = i + 1;
        [btnView addGestureRecognizer:tap];
    }
}

- (void)tapClick:(UITapGestureRecognizer *)tap
{
    NSInteger index = tap.view.tag;
    FirstCellModel *model = self.firstModelArray[index - 1];
    if (index == 1) {
        ProgramListViewController *program = [[ProgramListViewController alloc] init];
        program.urlStr = KMoreRankURL;
        program.titleStr = model.title;
        [self.navigationController pushViewController:program animated:YES];
    }else if (index == 3) {
        OtherProgramViewController *otherVC = [[OtherProgramViewController alloc] init];
        otherVC.urlStr = KHotRankURL;
        otherVC.indexC = 3;
        otherVC.titleStr = model.title;
        [self.navigationController pushViewController:otherVC animated:YES];
    } else if (index == 4) {
        ListenMoreViewController *vc = [[ListenMoreViewController alloc] init];
        vc.type = @"听";
        vc.code = self.code;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        self.cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"myCell" forIndexPath:indexPath];
        [self setupFirstCell];
        return _cell;
    }else if (indexPath.section == 1){
        RecommendCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"recommendCell" forIndexPath:indexPath];
        XiaoBianMoreModel *model = self.modelArray[indexPath.row];
        [cell setDataWithModel:model];
        return cell;
    }else if (indexPath.section == 2){
        NSArray *arr = self.arrayDic[@"听上海"];
        XiaoBianMoreModel *model = arr[indexPath.row];
        RecommendCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"recommendCell" forIndexPath:indexPath];
        [cell setDataWithModel:model];
        return cell;
    }else if (indexPath.section == 3){
        GoodListCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"goodListCell" forIndexPath:indexPath];
        NSArray *arr = self.arrayDic[@"精品听单"];
        GoodListModel *model = arr[indexPath.row];
        [cell setDataWithModel:model];
        return cell;
    }else{
        RecommendCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"recommendCell" forIndexPath:indexPath];
        NSArray *arr = self.arrayDic[self.titleArray[indexPath.section - 4]];
        XiaoBianMoreModel *model = arr[indexPath.row];
        [cell setDataWithModel:model];
        return cell;
    }
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    if (section == 0) {
        return UIEdgeInsetsMake(0, 0, 0, 0);
    }else{
        return UIEdgeInsetsMake(5, 5, 5, 5);
    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    TrackListDetailViewController *vc = [[TrackListDetailViewController alloc] init];
    if (indexPath.section == 1) {
        XiaoBianMoreModel *model = self.arrayDic[@"first"][indexPath.row];
        vc.model = model;
        [self.navigationController pushViewController:vc animated:YES];
    } else if (indexPath.section == 2) {
        XiaoBianMoreModel *model = self.arrayDic[@"听上海"][indexPath.row];
        vc.model = model;
        [self.navigationController pushViewController:vc animated:YES];
    } else if (indexPath.section == 3) {
        GoodListModel *model = self.arrayDic[@"精品听单"][indexPath.row];
        GoodListenListTableViewController *vc = [[GoodListenListTableViewController alloc] init];
        vc.myId = model.specialId;
        [self.navigationController pushViewController:vc animated:YES];
    } else if (indexPath.section == 4) {
        
    } else {
        XiaoBianMoreModel *model = self.arrayDic[self.titleArray[indexPath.section - 4]][indexPath.row];
        vc.model = model;
        [self.navigationController pushViewController:vc animated:YES];
    }
}


@end
